var db = require('../conf/db')
const jwtUtil = require('../public/utils/jwt')
let dayjs = require('dayjs')
let jwt = new jwtUtil()

   

const getNotice = async(req, res) => {
    let sqlcount='SELECT count(*) count FROM `mdm`.`notice` where 1=1'
    let sql = 'SELECT * FROM `mdm`.`notice` where 1=1 '
    let data = req.body
        if (data.formData&&data.formData.title) {
            sql += ' and title like "%' + data.formData.title + '%"'
        }
        if (data.formData&&data.formData.content) {
            sql += ' and content like "%' + data.formData.content + '%"'
        }
        
        sql+='and createdate >= (select createdate from notice order by id limit '+ (data.listQuery.page-1)*data.listQuery.limit +', 1) ORDER  BY createDate  limit  '+ data.listQuery.limit
console.log(sql)
    
        db.query(sql, [], function(results, fields) {
        let data=results
        for (let i = 0; i < data.length; i++) {
            const element = data[i];
            results[i].createdate = dayjs(data[i].createdate).format('YYYY-MM-DD HH:mm:ss')
            
        }
        db.query(sqlcount, [], function(counts, fields) {
            console.log(counts)
            // 以json的形式返回
            res.send({ code: 20000, data:{items:results,total:counts[0].count} })
    }) 

        
    }) 
}

const delNotice = async(req, res) => {
    let data = req.body
    let sql = 'DELETE FROM `mdm`.`notice` WHERE `id` = "' + data.id + '"'
    db.query(sql, [], function(results, fields) {
        // 以json的形式返回
        res.send({ code: 20000, data: results })
    })
}

const insertNotice = async(req, res) => {
    let data = req.body
    let user = jwt.verifyToken(req.headers['x-token'])
    let loginName=user.data.loginName
  
    let sql = 'INSERT INTO `mdm`.`notice`( `title`,`content`, `createdate`, `creator`, `status`) VALUES ( "'+(data.title ? data.title : '')+'","' + (data.content ? data.content : '') + '",now(), "' + (loginName ? loginName : '') + '", "' + (data.status ? data.status : '0') + '")'
    db.query(sql, [], function(results, fields) {
        // 以json的形式返回
        res.send({ code: 20000, data: results })


    })
}
const editNotice = async(req, res) => {
    let data = req.body
    let sql = 'UPDATE `mdm`.`notice` SET '
    for (const key in data) {
        if (data[key]) {
            if (key == 'id' || key == 'createdate' ) {
                continue
            }
            sql += key + '="' + data[key] + '",'
        }
    }
    sql = sql.substring(0, sql.length - 1)
    sql += ' WHERE `id` = "' + data.id + '"'
    db.query(sql, [], function(results, fields) {
        // 以json的形式返回

        res.send({ code: 20000, data: results })


    })
}

module.exports = {
    getNotice,
    editNotice,
    insertNotice,
    delNotice,
}